﻿using System;
using System.Collections;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
using ToolUtil;
using zyconfig;
using zyui;

namespace zymain
{
    public partial class FrmLtjy : Form
    {
        private string dztm, jszh;
        private bool flag=true,wj=false,gh=false;
        private string strerr = string.Empty;
        ProcessShareData obj = new ProcessShareData();
        //进程间网络通讯配置
        private IPAddress ipAddress;
        private string ip;
        private int port;
        private TcpClient client;
        private bool clientf = false;
        private string protype;
        public FrmLtjy()
        {
            InitializeComponent();
        }

        private void FrmLtjy_Load(object sender, EventArgs e)
        {
            ArrayList mylist = new ArrayList();
            mylist.Add(new DictionaryEntry("0", "借阅"));
            mylist.Add(new DictionaryEntry("1", "归还"));
            mylist.Add(new DictionaryEntry("2", "违章处罚"));
            mylist.Add(new DictionaryEntry("3", "赔书"));
            mylist.Add(new DictionaryEntry("4", "交款"));
            this.czKay.ValueMember = "Key";
            this.czKay.DisplayMember = "Value";
            this.czKay.DataSource = mylist;
            cmbBind(this.czKay, 30);
            this.bookPanel.Visible = false;
        }
        public static void cmbBind(ComboBox list, int itemHeight)
        {
            list.DropDownStyle = ComboBoxStyle.DropDownList;
            list.ItemHeight = itemHeight;
            list.DrawMode = DrawMode.OwnerDrawFixed;
            list.DrawItem += new DrawItemEventHandler(delegate (object sender, DrawItemEventArgs e)
            {
                if (e.Index < 0)
                {
                    return;
                }
                e.DrawBackground();
                e.DrawFocusRectangle();
                e.Graphics.DrawString(((DictionaryEntry)list.Items[e.Index]).Value.ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds.X, e.Bounds.Y + 5);
            });
        }

        private void czKay_selectedIndexChanged(object sender, EventArgs e)
        {
            int index = Convert.ToInt32(this.czKay.SelectedValue);
            switch (index)
            {
                case 0:
                    wj = true;
                    gh = false;
                    this.dztmTxt.ReadOnly = false;
                    break;
                case 1:
                    wj = false;
                    gh = true;
                    this.dztmTxt.Text = "";
                    this.dztmTxt.ReadOnly = true;
                    this.btmTxt.Focus();
                    break;
            }
        }
        private void setError()
        {
            this.jgTxt.Text = strerr;
            this.btmTxt.ReadOnly = true;
            this.jgTxt.Visible = true;
            this.dztmTxt.Text = "";
            this.dztmTxt.Focus();
        }
        private void dztm_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                //LtSettings.GetCqfk("21030223","");
                this.dztm = this.dztmTxt.Text.Trim();
                double qk = 0.00; int ywj = 0, kwj = 0;
                string dzxm = string.Empty, szdw = string.Empty, type = string.Empty, dzjb = string.Empty;
                string sex = string.Empty;
                this.dzzpBox.Image = null;
                if (!string.IsNullOrEmpty(dztm))
                {
                    using (DbOperHandler _open = new Common().Doh())
                    {
                        _open.Reset();
                        _open.ConditionExpress = "读者条码='" + dztm + "'";
                        if (_open.Exist("读者库"))
                        {
                            if (_open.GetField("读者库", "照片") != System.DBNull.Value)
                            {
                                Byte[] byteImageCol = (Byte[])(_open.GetField("读者库", "照片"));
                                MemoryStream stmImageCol = new MemoryStream(byteImageCol);
                                dzzpBox.Image = Image.FromStream(stmImageCol);
                            }
                            this.dztm = _open.GetField("读者库", "读者条码").ToString().Trim();
                            this.jszh = _open.GetField("读者库", "借书证号").ToString().Trim();
                            szdw = _open.GetField("读者库", "单位").ToString().Trim();
                            dzxm = _open.GetField("读者库", "姓名").ToString().Trim();
                            dzjb = _open.GetField("读者库", "读者级别").ToString().Trim();
                            sex = _open.GetField("读者库", "性别").ToString().Trim();
                            type = _open.GetField("读者库", "挂失注销").ToString().Trim();
                            qk += Convert.ToDouble(_open.GetField("读者库", "欠罚款").ToString().Trim());
                            qk += Convert.ToDouble(_open.GetField("读者库", "欠赔款").ToString().Trim());
                            ywj = Convert.ToInt32(_open.GetField("读者库", "已外借").ToString().Trim());
                            kwj = Convert.ToInt32(_open.GetField("读者库", "可外借").ToString().Trim());
                            flag = true;
                        }
                        else
                        {
                            _open.Reset();
                            _open.ConditionExpress = "借书证号='" + dztm + "'";
                            if (_open.Exist("读者库"))
                            {
                                if (_open.GetField("读者库", "照片") != System.DBNull.Value)
                                {
                                    Byte[] byteImageCol = (Byte[])(_open.GetField("读者库", "照片"));
                                    MemoryStream stmImageCol = new MemoryStream(byteImageCol);
                                    dzzpBox.Image = Image.FromStream(stmImageCol);
                                }
                                this.jszh = _open.GetField("读者库", "借书证号").ToString().Trim();
                                szdw = _open.GetField("读者库", "单位").ToString().Trim();
                                dzxm = _open.GetField("读者库", "姓名").ToString().Trim();
                                dzjb = _open.GetField("读者库", "读者级别").ToString().Trim();
                                sex = _open.GetField("读者库", "性别").ToString().Trim();
                                type = _open.GetField("读者库", "挂失注销").ToString().Trim();
                                qk += Convert.ToDouble(_open.GetField("读者库", "欠罚款").ToString().Trim());
                                qk += Convert.ToDouble(_open.GetField("读者库", "欠赔款").ToString().Trim());
                                ywj = Convert.ToInt32(_open.GetField("读者库", "已外借").ToString().Trim());
                                kwj = Convert.ToInt32(_open.GetField("读者库", "可外借").ToString().Trim());
                                flag = true;
                            }
                        }
                    }
                    qk = Math.Round(qk, 2);
                    this.xhTxt.Text = this.jszh;
                    this.xmTxt.Text = dzxm;
                    this.dwTxt.Text = szdw;
                    this.qkTxt.Text = qk.ToString();
                    this.kwjTxt.Text = kwj.ToString();
                    this.ywjTxt.Text = ywj.ToString();
                    this.sexTxt.Text = sex;
                    this.jbTxt.Text = dzjb;
                    if (string.IsNullOrEmpty(this.jszh)){
                        this.flag = false;
                        strerr = "该读者不存在！！";
                        this.setError();
                        return;
                    }
                    this.dtmTxt.Text = this.dztm;
                    if (ywj.ToString().Trim().Equals(kwj.ToString().Trim()))
                    {
                        this.flag = false;
                        strerr = "该读者借阅已达上限，不可再借！！";
                        this.setError();
                        return;
                    }
                    if (!string.IsNullOrEmpty(type))
                    {
                        this.flag = false;
                        strerr = "该读者已被【" + type + "】";
                        this.setError();
                        return;
                    }
                    if (qk > 0)
                    {
                        this.flag = false;
                        strerr = "该读者尚有欠款未缴清！欠款金额为：" + qk;
                        this.setError();
                        return;
                    }
                    this.flag = Reader.checkOverdue(dztm, out strerr);
                    if (this.flag)
                    {
                        this.jgTxt.Visible = false;
                        this.btmTxt.ReadOnly = false;
                        this.btmTxt.Focus();
                    }
                    else
                    {
                        this.setError();
                    }
                }
            }
        }

        private void serverPro()
        {
            string path = Application.StartupPath + @"\config\zylib.ini";
            if (File.Exists(path))
            {
                try
                {
                    IniFiles iniFiles = new IniFiles(path);
                    ip = iniFiles.IniReadValue("一卡通", "IPADDRESS");
                    this.protype = iniFiles.IniReadValue("一卡通", "PROTYPE");
                    port = Convert.ToInt32(iniFiles.IniReadValue("一卡通", "PORT"));
                    Console.WriteLine(ip);
                    //this.protype = IniFunc.getString("ykt", "PROTYPE", "", path);
                    // ip = IniFunc.getString("一卡通", "IPADDRESS", "", path).Trim();
                    //port = Convert.ToInt32(IniFunc.getString("ykt", "PORT", "", path));
                    ipAddress = IPAddress.Parse(ip);
                    client = new TcpClient();
                    client.Connect(ipAddress, port);
                    clientf = true;
                }
                catch(Exception ex)
                {
                    clientf = false;
                    dlLabel.Text = "第三方对接程序未启动...";
                    Console.WriteLine(ex.Message);
                }
            }
        }
        protected override void DefWndProc(ref Message m)
        {
            if (m.Msg == 0x104)
            {
                m.Result = (IntPtr)333;
                return;
            }
            else
            {}
            base.DefWndProc(ref m);
        }
        private int q = 0;
        private void dztmTxt_MouseClick(object sender, MouseEventArgs e)
        {
            string dztm = this.dztmTxt.Text.Trim();
            if (string.IsNullOrEmpty(dztm))
            {
                if (!string.IsNullOrEmpty(this.ip))
                {
                    dlLabel.Text = "正在读取校园卡...";
                }
                else
                {
                    dlLabel.Text = "未设置一卡通对接...";
                }
                this.serverPro();
                if (this.clientf && this.protype.Equals("Socke"))
                {
                    NetworkStream stream = client.GetStream();
                    string message = "getcode";
                    byte[] buffer = Encoding.ASCII.GetBytes(message);
                    stream.Write(buffer, 0, buffer.Length);
                    Console.WriteLine("Sent: " + message);
                    buffer = new byte[1024];
                    int bytes = stream.Read(buffer, 0, buffer.Length);
                    string message1 = Encoding.ASCII.GetString(buffer, 0, bytes);
                    Console.WriteLine("Received: " + message1);
                    if (!string.IsNullOrEmpty(message1) && !message1.Equals("0"))
                    {
                        this.dztmTxt.Text = message1;
                        KeyPressEventArgs e1 = new KeyPressEventArgs('\r');
                        dztm_KeyPress(this.dztmTxt, e1);
                    }
                    else
                    {
                        dlLabel.Text = "读取卡片失败...";
                    }
                }
                if (this.protype.Equals("Memory"))
                {
                    obj.reclose();
                    obj.init();
                    obj.WriteData2SharedMemory(q.ToString(), null);
                    if (obj.m_str.Length > 0)
                    {
                        this.dztmTxt.Text = obj.m_str;
                        KeyPressEventArgs e1 = new KeyPressEventArgs('\r');
                        dztm_KeyPress(this.dztmTxt, e1);
                        dlLabel.Text = "";
                    }
                    else
                    {
                        dlLabel.Text = "读取卡片失败...";
                    }
                    q++;
                }
            }
        }

        private void ltjy_FormClosing(object sender, FormClosingEventArgs e)
        {
            obj.close();
        }

        private void btm_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                string btm = this.btmTxt.Text.Trim();
                if (!string.IsNullOrEmpty(btm))
                {
                    if (this.wj)
                    {
                        int xnks = BookSetting.getXnks(btm, out strerr);
                        if (xnks == 0)
                        {
                            this.jgTxt.Text = strerr;
                            this.jgTxt.Visible = true;
                            this.btmTxt.Text = "";
                            this.btmTxt.Focus();
                        }
                        else
                        {
                            if (Reader.getBkwj(this.dztm, xnks, out strerr))
                            {
                                int kwjs = Reader.getkwj(this.dztm, xnks);
                                Console.WriteLine("可外借" + kwjs);
                                if (kwjs > 0)
                                {

                                }
                                else
                                {
                                    this.jgTxt.Text = "读者在该库室的可借数已达上限！";
                                    this.jgTxt.Visible = true;
                                    this.btmTxt.Text = "";
                                    this.btmTxt.Focus();
                                }
                            }
                            else
                            {
                                this.jgTxt.Text = strerr;
                                this.jgTxt.Visible = true;
                                this.btmTxt.Text = "";
                                this.btmTxt.Focus();
                            }
                        }
                    }
                    if (gh)
                    {

                    }
                }
            }
        }

        private void dztm_TextChanged(object sender, EventArgs e)
        {
            string dztm = this.dztmTxt.Text.Trim();
            if (string.IsNullOrEmpty(dztm))
            {
                obj.reclose();
                obj.init();
                obj.WriteData2SharedMemory(q.ToString(), null);
                //Thread.Sleep(2);
                if (obj.m_str.Length > 0)
                {
                    this.dztmTxt.Text = obj.m_str;
                    KeyPressEventArgs e1 = new KeyPressEventArgs('\r');
                    dztm_KeyPress(this.dztmTxt, e1);
                }
                q++;
            }
        }
    }
}
